package com.atguigu.gulimall.product.service.impl;

import cn.hutool.json.JSONUtil;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.SkuInfoDao;
import com.atguigu.gulimall.product.entity.SkuImagesEntity;
import com.atguigu.gulimall.product.entity.SkuInfoEntity;
import com.atguigu.gulimall.product.entity.SpuInfoDescEntity;
import com.atguigu.gulimall.product.feign.SeckillFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.SeckillSkuVo;
import com.atguigu.gulimall.product.vo.SkuItemSaleAttrVo;
import com.atguigu.gulimall.product.vo.SkuItemVo;
import com.atguigu.gulimall.product.vo.SpuItemAttrGroupVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Resource
    private SkuImagesService skuImagesService;
    @Resource
    private SpuInfoDescService spuInfoDescService;
    @Resource
    private AttrGroupService attrGroupService;
    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    private SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        LambdaQueryWrapper<SkuInfoEntity> wrapper = new LambdaQueryWrapper<>();

        String key = (String)params.get("key");
        wrapper.and(StringUtils.hasText(key), w -> w.eq(SkuInfoEntity::getSkuId, key).or().like(SkuInfoEntity::getSkuName, key));

        String catelogId = (String)params.get("catelogId");
        wrapper.eq(StringUtils.hasText(catelogId) && !"0".equalsIgnoreCase(catelogId), SkuInfoEntity::getCatalogId, catelogId);

        String brandId = (String)params.get("brandId");
        wrapper.eq(StringUtils.hasText(brandId) && !"0".equalsIgnoreCase(brandId), SkuInfoEntity::getBrandId, brandId);

        String min = (String)params.get("min");
        wrapper.ge(StringUtils.hasText(min), SkuInfoEntity::getPrice, min);

        String max = (String)params.get("max");
        if (StringUtils.hasText(max)) {
            try {
                // 将字符串转成 BigDecimal，前端可能传入的不是数字格式的字符串，所以需要捕获异常
                BigDecimal bigDecimal = new BigDecimal(max);
                // 同时拼接大于等于和小于等于，需要保证一端不能为0
                wrapper.le( bigDecimal.compareTo(BigDecimal.ZERO) == 1, SkuInfoEntity::getPrice, max);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        return this.list(new LambdaQueryWrapper<SkuInfoEntity>()
                .eq(SkuInfoEntity::getSpuId, spuId));
    }

    /**
     * 根据 skuId 查询商品详情页需要展示的数据
     * @param skuId
     * @return
     */
    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {

        SkuItemVo skuItemVo = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            // 1 SKU 基本信息获取
            SkuInfoEntity skuInfoEntity = getById(skuId);
            skuItemVo.setInfo(skuInfoEntity);
            return skuInfoEntity;
        }, threadPoolExecutor);

        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync(skuInfoEntity -> {
            // 3 SKU 所属 SPU 的销售属性组合信息
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(skuInfoEntity.getSpuId());
            skuItemVo.setSaleAttrs(saleAttrVos);
        }, threadPoolExecutor);

        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync(skuInfoEntity -> {
            // 4 SKU 所属 SPU 的描述信息
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(skuInfoEntity.getSpuId());
            skuItemVo.setDesc(spuInfoDescEntity);
        }, threadPoolExecutor);

        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync(skuInfoEntity -> {
            // 5 SKU 所属 SPU 的规格参数信息
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(skuInfoEntity.getSpuId(), skuInfoEntity.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroupVos);
        }, threadPoolExecutor);


        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            // 2 SKU 图片信息获取
            List<SkuImagesEntity> imagesEntityList = skuImagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(imagesEntityList);
        }, threadPoolExecutor);

        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            R r = seckillFeignService.getSkuSeckillInfo(skuId);
            if (r.getCode() == 0) {
                Object data = r.get("data");
                SeckillSkuVo seckillSkuVo = JSONUtil.toBean(JSONUtil.toJsonStr(data), SeckillSkuVo.class);
                skuItemVo.setSeckillSkuVo(seckillSkuVo);
            }
        }, threadPoolExecutor);


        // 等待所有任务都完成
        // allOf() 不用添加 infoFuture，因为添加的 saleAttrFuture, descFuture, baseAttrFuture 都以 infoFuture 任务完成作为前提条件
        CompletableFuture.allOf(saleAttrFuture, descFuture, baseAttrFuture, imagesFuture, seckillFuture).get();

        return skuItemVo;
    }

    @Override
    public Map<Long, BigDecimal> getSkuPricesBySkuIdList(List<Long> skuIdList) {
        List<SkuInfoEntity> list = this.list(new LambdaQueryWrapper<SkuInfoEntity>().in(SkuInfoEntity::getSkuId, skuIdList));
        return list.stream().collect(Collectors.toMap(SkuInfoEntity::getSkuId, SkuInfoEntity::getPrice));
    }
}